﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYLitedbBase;

namespace DSPara
{
    public class Entity_SeqNoPara : TYLitedbBase.Entity_LiteDB_Base
    {
        public string SectionId { get; set; }
        public List<Entity_SeqNoItem> ListSeqNoItem { get; set; } = new List<Entity_SeqNoItem>();
    }

    public class Entity_SeqNoItem : TYLitedbBase.Entity_LiteDB_Base
    {
        public int AtLevel { get; set; }

        public int MinVal { get; set; }

        public int MaxVal { get; set; } 
    }

    public class SeqNoHelper
    {
        public string SectionId { get; set; }
        public List<Entity_SeqNoItem> ListSSeqNoItem { get; set; }
        private int SSeqNoCount = 0;

        public SeqNoHelper(string section, int sSeqNoCount)
        {
            SectionId = section;
            SSeqNoCount = sSeqNoCount;
            ListSSeqNoItem = new List<Entity_SeqNoItem>();
            for (int i = 0; i < sSeqNoCount; i++)
            {
                ListSSeqNoItem.Add(new Entity_SeqNoItem { AtLevel = i + 1,  MaxVal = 0, MinVal=0 });
            }
        }

        public Entity_SeqNoItem GetSeqNo(int fromSSeqNo)
        {
            var data = ListSSeqNoItem.FirstOrDefault(x => x.AtLevel == fromSSeqNo);
            if (data != null)
                return data;
            return null;
        }

        public void Init(Entity_SeqNoPara listData)
        {
            if (listData == null)
                return;
            for (int i = 0; i < ListSSeqNoItem.Count; i++)
            {
                var data = listData.ListSeqNoItem.FirstOrDefault(x => x.AtLevel == ListSSeqNoItem[i].AtLevel);
                if (data != null)
                {
                    ListSSeqNoItem[i].MaxVal = data.MaxVal;
                    ListSSeqNoItem[i].MinVal = data.MinVal;
                }
            }
        }
    }

    public class SeqNoDataCreator
    {
        private readonly string dbName;

        /// <summary>
        /// 这个是配置的数据库
        /// </summary>
        /// <param name="_dbName"></param>
        public SeqNoDataCreator(string _dbName)
        {
            dbName = _dbName;
        }

        public bool Init(SeqNoHelper offsetPara, ref string error)
        {
            var liteDBHelper = new LiteDB_BaseHelper<Entity_SeqNoPara>(dbName);
            if (liteDBHelper.Get(x => x.SectionId == offsetPara.SectionId, out Entity_SeqNoPara listData))
            {
                if (listData == null)
                {
                    error = "无批次分选!!";
                    return false;
                }
                offsetPara.Init(listData);
                return true;
            }
            else
            {
                error = $" 读取批次分选 异常!section:{offsetPara.SectionId}-本地文件为{LiteDBHelper.GetFileFullPath(dbName)} ";
            }
            return false;
        }
    }
}